package com.pi.pro.xcmg.am.was.web.monitor.controller;


import com.pi.common.CodesConstants;
import com.pi.common.utils.StringUtils;
import com.pi.framework.core.controller.BaseCrudController;
import com.pi.framework.core.service.ICrudService;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.dto.ResponseDto;
import com.pi.framework.dto.ResponseStatus;
import com.pi.monitor.base.dto.LaneStorageSummary;
import com.pi.monitor.base.dto.LineStorageSummary;
import com.pi.monitor.base.dto.LocationCell;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.common.vo.act.InventoryLineData;
import com.pi.pro.xcmg.am.was.fac.service.StorageViewService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.base.LocationLineDto;
import com.pi.wms.entity.TwaInventoryDetails;
import com.pi.wms.entity.TwaInventoryLotattr;
import com.pi.wms.entity.TwmBasLocation;
import com.pi.wms.entity.TwmBasMaterial;
import com.pi.wms.fac.LocationResolver;
import com.pi.wms.service.InventoryDetailsService;
import com.pi.wms.service.InventoryLotattrService;
import com.pi.wms.service.LocationService;
import com.pi.wms.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.sql.rowset.serial.SerialException;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/monitor/storagemap/query")
public class StoragemapApiController extends BaseCrudController<TwmBasLocation,Long> {

	public static final int MINUTES = 60;

	@Autowired
	private LocationService locationService;

	@Autowired
	private LocationResolver locationResolver;

	@Autowired
	private StorageViewService storageViewService;

	@Autowired
	private MaterialService materialService;

	@Autowired
	private InventoryDetailsService inventoryDetailsService;

	@Autowired
	private InventoryLotattrService lotattrService;

	protected String getPrefix() {
		return "storagemap";
	}

	@Override
	protected TwmBasLocation newModel(HttpServletRequest request) {
		return null;
	}

	@Override
	protected ICrudService<TwmBasLocation, Long> getCrudService() {
		return this.locationService;
	}

	@GetMapping(value = { "linedetails" })
	public ResponseDto getLineDetails(HttpServletRequest request){
		LocationCell[][] datas=null;
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
		String linenum="1";
		if (request.getParameter("linenum")!=null){
			linenum=request.getParameter("linenum");
		}
		datas=storageViewService.listAll(linenum);

		responseDto.setData(datas);
		return responseDto;
	}

	@GetMapping(value = { "linelayerdetails" })
	public ResponseDto getLineLayerDetails(HttpServletRequest request){
		LocationCell[] datas=null;
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
		String linenum="1";
		if (request.getParameter("linenum")!=null){
			linenum=request.getParameter("linenum");
		}
		String layernum="1";
		if (request.getParameter("layernum")!=null){
			layernum=request.getParameter("layernum");
		}
		datas=storageViewService.listAll(linenum,layernum);

		responseDto.setData(datas);
		return responseDto;
	}

	//按"排"汇总
	@GetMapping(value = { "linessummary" })
	public ResponseDto getLinesSummary(HttpServletRequest request){
		List<LineStorageSummary> datas=null;
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
		datas=storageViewService.lineSummary();

		responseDto.setData(datas);
		return responseDto;
	}


	//汇总整个仓库
	@GetMapping(value = { "summary" })
	public ResponseDto getSummaryLines(HttpServletRequest request){
		LineStorageSummary datas=null;
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
		datas=storageViewService.summary();

		responseDto.setData(datas);
		return responseDto;
	}

	@GetMapping(value = { "v2/linedetails" })
	public ResponseDto getFlexLineDetails(HttpServletRequest request){
		LocationCell[][] datas=null;
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
		String linecode="L01/R01";
		if (request.getParameter("linecode")!=null){
			linecode=request.getParameter("linecode");
		}
		datas=storageViewService.listAll(linecode,true);

		responseDto.setData(datas);
		return responseDto;
	}

    //按"巷道"汇总
    @GetMapping(value = { "v2/lanessummary" })
    public ResponseDto getLanesSummary(HttpServletRequest request){
        List<LaneStorageSummary> datas=null;
        ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
        int size=1;
        if (request.getParameter("size")!=null){
            String lanesize=request.getParameter("size");
            size= StringUtils.getIntValue(lanesize);
        }
        if (size<=0){
            size=1;
        }
        datas=storageViewService.laneSummary(size);
        responseDto.setData(datas);
        return responseDto;
    }

	//汇总整个仓库
	@GetMapping(value = { "v2/summary" })
	public ResponseDto getSummaryLanes(HttpServletRequest request){
		LaneStorageSummary datas=null;
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
        int size=1;
        if (request.getParameter("size")!=null){
            String lanesize=request.getParameter("size");
            size= StringUtils.getIntValue(lanesize);
        }
        if (size<=0){
            size=1;
        }
		datas=storageViewService.summary(size);

		responseDto.setData(datas);
		return responseDto;
	}

	//显示库位(托盘)明细
	@GetMapping(value = { "details" })
	public ResponseDto getLocationContainerDetails(HttpServletRequest request){
		ResponseDto responseDto=new ResponseDto(ResponseStatus.success);
        responseDto.setData(new ArrayList<>());
        String loccode="";
        if (request.getParameter("locationcode")!=null){
            loccode=request.getParameter("locationcode");
        }
        if (StringUtils.isNullOrBlank(loccode)){
            return responseDto;
        }
        LocationLineDto loc=this.locationResolver.lookup(XcmgAmConstants.DIVISION_WH101_ID, loccode.trim());
        if (loc==null){
            return responseDto;
        }
        List<TwaInventoryDetails> storages=this.inventoryDetailsService.findByLocationId(loc.getLocationId());
        if ((storages==null) || (storages.size()==0)){
            return responseDto;
        }
        List<InventoryLineData> lines=this.translateTo(storages);
		responseDto.setData(lines);
		return responseDto;
	}

    private List<InventoryLineData> translateTo(List<TwaInventoryDetails> storages){
        List<InventoryLineData> lines=new ArrayList<>();
        if ((storages==null)||(storages.size()==0)){
            return lines;
        }
        InventoryLineData line=null;
        TwmBasMaterial mat=null;
        TwaInventoryLotattr lotattr=null;
        try{
            for (TwaInventoryDetails d:storages){
                if (d==null){
                    continue;
                }
                mat=this.materialService.lookup(d.getMaterialId());
                if (mat==null){
                    continue;
                }

                line=new InventoryLineData();
                line.setId(d.getId());
                line.setCategoryname("'外购物料入库");
                if (XcmgAmConstants.WORK_SOURCE_KIT.equalsIgnoreCase(d.getReserveCode())){
                    line.setCategoryname("生产配盘入库");
                }
                if (XcmgAmConstants.WORK_SOURCE_SELF_MADE.equalsIgnoreCase(d.getReserveCode())){
                    line.setCategoryname("自制物料入库");
                }
                if (XcmgAmConstants.WORK_SOURCE_OTHER.equalsIgnoreCase(d.getReserveCode())){
                    line.setCategoryname("其它物料入库");
                }
                line.setMaterialcode(mat.getCode());
                line.setMaterialname(mat.getName());
                lotattr=this.lotattrService.lookup(d.getLotnoId());

                line.setWbsnumber("");
                line.setSuppliercode("");
                if (lotattr!=null){
                    line.setWbsnumber(lotattr.getLotattr07());
                    line.setSuppliercode(lotattr.getLotattr06());
                }
                line.setContainernumber(d.getContainNumber());
                line.setQuantity(d.getQty().stripTrailingZeros().toPlainString());
                line.setQuantityallocated("0");
                if ((d.getQtyAllocated()!=null) && (d.getQtyAllocated().compareTo(BigDecimal.ZERO)>0)){
                    line.setQuantityallocated(d.getQtyAllocated().stripTrailingZeros().toPlainString());
                }
                line.setUomcode(CodesConstants.UOM_EACH);
                line.setLocationcode(d.getLocCode());
                line.setCustomercode(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM);
                line.setXwmslotnumber(d.getUdf07());
                if (d.getReceiveTime()!=null){
                    line.setReceivetime(DateUtils.format(d.getReceiveTime(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
                }else{
                    line.setReceivetime(DateUtils.format(d.getCreatedDate(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
                }
                line.setImageurl(d.getLpn());
                line.setStatusname("可用");
                if (WmsConstants.STORAGE_STATUS_LOCK.equalsIgnoreCase(d.getStatus())){
                    line.setStatusname("锁定");
                }
                if (line!=null){
                    lines.add(line);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return lines;
    }


    /**
     * 查询图片的接口ip地址和端口，
     */
    private String imageIpPort = "http://localhost:8088";
    private String loadImageUrl = imageIpPort+"/apiImages/convertPath";

    /**
     * 根据库位绑定的图片存储路径，返回抓拍程序中，可以访问的图片url链接
     * @param imagePath
     * @return
     */
    @GetMapping("/loadImg")
    public Map<String, Object> loadImg(@RequestParam String imagePath){

        log.info("imagePath: "+imagePath);
        // 调用 图片接口，获取图片的url访问路径
        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 构建请求参数
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("path", imagePath); // 根据实际参数名调整
        // 创建请求实体
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
        // 接口URL（根据实际情况修改）
        try {
            // 发送POST请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    loadImageUrl,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            // 获取响应结果
            if (response.getStatusCode() == HttpStatus.OK) {
                System.out.println("response: " + response.getBody());
                Map obj = response.getBody();
                System.out.println("map: "+obj);
                Map<String, Object> map = new HashMap<>();
                map.put("success", true);
                map.put("webUrl", imageIpPort+obj.get("webUrl"));
                map.put("fileName", obj.get("fileName"));
                return map;
            } else {
                throw new RuntimeException("API调用失败，状态码: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("调用接口异常: " + e.getMessage(), e);
        }
    }


}
